import moment from 'moment/moment'
import {getAccessRecordsDB} from './datastore'

export function recordMovieAccessRecords(year, name) {
    return recordAccessRecords('movieAccessRecords', `${year}.${name}`)
}

export function recordVideoAccessRecords(videoFileName) {
    return recordAccessRecords('videoAccessRecords', videoFileName)
}

const accessRecordsDB = getAccessRecordsDB()

function recordAccessRecords(recordsName, recordsKey) {
    const records = accessRecordsDB.get(recordsName).value()

    const ctime = moment().format('YYYY-MM-DD HH:mm:ss')

    let thisRecord = records[recordsKey]
    if (!thisRecord) {
        records[recordsKey] = {
            accessCount: 1,
            lastAccessTime: ctime,
            accessTimes: [ctime]
        }
    } else {
        thisRecord.accessCount++
        thisRecord.lastAccessTime = ctime
        thisRecord.accessTimes.push(ctime)
    }

    accessRecordsDB.set(recordsName, records).write()

    console.log(recordsKey, thisRecord)
    return thisRecord
}

export function sortByAccessRecords(aRecords, bRecords) {
    let bCount = bRecords?.accessCount ?? 0
    let aCount = aRecords?.accessCount ?? 0
    const sort = bCount - aCount
    if (sort === 0) {
        let bTime = bRecords?.lastAccessTime ?? '0'
        let aTime = aRecords?.lastAccessTime ?? '0'
        return bTime.localeCompare(aTime)
    }
    return sort
}
